import { useContext, useMemo } from "react";
import { GlobalModel } from "@/ui/context";
import { getValueOrDie } from "@common/utils";
import { useDebounceFn, useMemoizedFn, useMount, useSafeState } from "ahooks";
import type { QuickMessage } from "@common/models";
import { Form, Modal, message } from "antd";
import * as rpcApis from "@/ui/utils/rpc/quickMessage";
import { v4 as uuid } from "uuid";
import events from "@/ui/events";

export function useViewModel() {
  const globalModel = getValueOrDie(useContext(GlobalModel));
  const { quickMessages } = globalModel;

  const [editorVisible, setEditorVisible] = useSafeState(false);
  const [target, setTarget] = useSafeState<Partial<QuickMessage> | undefined>();
  const [form] = Form.useForm();

  const onCreateClick = useMemoizedFn(() => {
    setEditorVisible(true);
  });
  const onSubmitClick = useMemoizedFn(async () => {
    try {
      const record: QuickMessage = await form.validateFields();
      if (record.id) {
        await rpcApis.update({ record });
        message.success(`修改【${record.id}】成功`);
      } else if ((await rpcApis.has({ shortcut: record.shortcut })).existed) {
        message.error(`创建失败：存在缩写为【${record.shortcut}】的话术`);
        return;
      } else if ((await rpcApis.has({ title: record.title })).existed) {
        message.error(`创建失败：存在标题为【${record.title}】的话术`);
        return;
      } else {
        record.id = uuid();
        await rpcApis.create({ record });
        message.success(`新增【${record.title}】成功`);
      }
      await loadRecords.run();
      onCancelClick();
    } catch (err) {
      console.error("error:", err);
      message.error((err as Error)?.message ?? `${err}`);
    }
  });
  const onDeleteClick = (record: QuickMessage) => {
    Modal.confirm({
      title: "删除话术",
      content: `确定要删除话术【${record.title}:${record.shortcut}】?`,
      cancelText: "我再想想",
      okText: "删除",
      okType: "danger",
      onOk: async () => {
        await rpcApis.remove({ id: record.id });
        message.success(`删除【${record.title}】成功`);
        await loadRecords.run();
        onCancelClick();
      },
    });
  };
  const onEditClick = async (record: QuickMessage) => {
    form.setFieldsValue(record);
    setTarget(record);
    setEditorVisible(true);
  };
  const onCancelClick = useMemoizedFn(() => {
    setEditorVisible(false);
    setTarget(undefined);
    form.resetFields();
  });

  const loadRecords = useDebounceFn(
    async () => {
      globalModel.quickMessages = await rpcApis.load();
    },
    {
      leading: true,
      trailing: false,
    },
  );

  const onRecordSelect = (record: QuickMessage) => () => {
    events.QuickMessage.Select.emit({ record });
  };

  const targetRecords = useMemo(() => {
    const filter = globalModel.quickMessageInput;
    if (!filter) {
      return quickMessages;
    }

    const startsWith = quickMessages.filter((r) =>
      r.shortcut.startsWith(filter),
    );
    const includes = quickMessages.filter(
      (r) => !startsWith.includes(r) && r.shortcut.includes(filter),
    );
    return startsWith.concat(includes);
  }, [globalModel.quickMessageInput, quickMessages]);

  useMount(() => loadRecords.run());

  return {
    editorVisible,
    target,
    form,
    globalModel,
    targetRecords,

    onCreateClick,
    onEditClick,
    onDeleteClick,
    onSubmitClick,
    onCancelClick,
    onRecordSelect,
  };
}
